<template>
  <div class="evaluation-detail" v-loading="loading">
    <div class="header">
      <h2>{{ scale?.name }}</h2>
      <p class="description">{{ scale?.description }}</p>
    </div>

    <div class="questions" v-if="questions.length > 0">
      <el-form ref="formRef" :model="form" label-position="top">
        <div v-for="(question, index) in questions" :key="question.id" class="question-item">
          <h3>{{ index + 1 }}. {{ question.content }}</h3>
          
          <!-- 选择题 -->
          <el-form-item 
            v-if="question.type !== 'TEXT'"
            :prop="`answers.${question.id}`"
            :rules="[{ required: true, message: '请选择答案', trigger: 'change' }]"
          >
            <el-radio-group v-model="form.answers[question.id]">
              <el-radio 
                v-for="option in question.options" 
                :key="option.id" 
                :label="option.id"
              >
                {{ option.content }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 文本题 -->
          <el-form-item 
            v-else
            :prop="`answers.${question.id}`"
            :rules="[{ required: true, message: '请填写答案', trigger: 'blur' }]"
          >
            <el-input 
              v-model="form.answers[question.id]" 
              type="textarea" 
              :rows="3" 
              placeholder="请输入您的答案"
            ></el-input>
          </el-form-item>
        </div>

        <div class="form-footer">
          <el-button type="primary" @click="submitForm">提交答案</el-button>
        </div>
      </el-form>
    </div>

    <el-empty v-else-if="!loading" description="暂无题目"></el-empty>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const scale = ref(null)
const questions = ref([])
const formRef = ref()
const form = ref({
  answers: {}
})

// 获取量表详情
const fetchScaleDetail = async () => {
  loading.value = true
  try {
    const { data } = await request.get(`/admin/scales/${route.params.id}`)
    scale.value = data
  } catch (error) {
    console.error('Error fetching scale detail:', error)
    ElMessage.error('获取量表详情失败')
  }
}

// 获取量表题目
const fetchQuestions = async () => {
  try {
    const { data } = await request.get(`/admin/scales/${route.params.id}/questions`)
    questions.value = data || []
    // 初始化答案对象
    questions.value.forEach(question => {
      form.value.answers[question.id] = ''
    })
  } catch (error) {
    console.error('Error fetching questions:', error)
    ElMessage.error('获取题目失败')
  } finally {
    loading.value = false
  }
}

// 提交测评
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const answers = Object.entries(form.value.answers).map(([questionId, answer]) => {
          const question = questions.value.find(q => q.id === parseInt(questionId))
          if (question.type === 'TEXT') {
            return {
              questionId: parseInt(questionId),
              answer: answer,      // 文本题答案就是输入内容
              content: answer      // 文本题内容就是输入内容
            }
          } else {
            const option = question.options.find(opt => opt.id === answer)
            return {
              questionId: parseInt(questionId),
              answer: option.score.toString(),  // 单选题答案是选项的分数
              content: option.content           // 单选题内容是选项的内容
            }
          }
        })

        const { data } = await request.post(`/admin/scales/${route.params.id}/submit`, {
          answers: answers
        })
        ElMessage.success('提交成功')
        router.push(`/evaluation/${data}/result`)
      } catch (error) {
        console.error('Error submitting evaluation:', error)
        ElMessage.error('提交失败')
      }
    }
  })
}

onMounted(async () => {
  await fetchScaleDetail()
  await fetchQuestions()
})
</script>

<style scoped>
.evaluation-detail {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 40px;
}

.description {
  color: #666;
  margin-top: 10px;
}

.question-item {
  margin-bottom: 30px;
  padding: 20px;
  border-radius: 8px;
  background-color: #f8f9fa;
}

.question-item h3 {
  margin-bottom: 15px;
  color: #333;
}

.form-footer {
  margin-top: 40px;
  text-align: center;
}

:deep(.el-radio) {
  margin-right: 30px;
  margin-bottom: 10px;
}

:deep(.el-radio__label) {
  white-space: normal;
}
</style> 